package com.panda.ws;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.panda.sys.entity.User;
import com.panda.utils.contantUtil;

@ServerEndpoint(value = "/webSocket", configurator = HttpSessionConfigurator.class)
public class WebSocketServer {
	private User user;
	private HttpSession httpSession;
	private static final AtomicInteger onlineCount = new AtomicInteger(0);
	public static Map<Long, Session> sessionMap = new HashMap<Long, Session>();

	public WebSocketServer() {
		onlineCount.addAndGet(1);
	}

	@OnOpen
	public void onOpen(Session session, EndpointConfig config) {
		this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
		user = (User) httpSession.getAttribute(contantUtil.SESSION_USER);
		sessionMap.put(user.getId(), session);
	}

	@OnMessage
	public void onMessage(String message, Session session) {
		Message mes = JSON.parseObject(message, Message.class);
		mes.setTime(new Date());
		mes.setFrom(user.getName());
		mes.setFromId(user.getId());
		Session to = sessionMap.get(mes.getTo());
		if(to==session){
			mes.setFrom("系统");
			mes.setContent("不能给自己发消息！");
			broadcast(JSON.toJSONString(mes), session);
		}else if (to == null) {
			mes.setFrom("系统");
			mes.setFromId(mes.getTo());;
			mes.setContent("用户已离线");
			broadcast(JSON.toJSONString(mes), session);
		} else {
			broadcast(JSON.toJSONString(mes), to);
		}
	}

	private void broadcast(String message, Session session) {
		session.getAsyncRemote().sendText(message);
	}

	@OnClose
	public void onClose() {
		sessionMap.remove(user.getId());
	}

}